<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="竞赛名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入竞赛名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="作品名称" prop="reserved1">
        <el-input
          v-model="queryParams.reserved1"
          placeholder="请输入作品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="参赛学生" prop="reserved2">
        <el-input
          v-model="queryParams.reserved2"
          placeholder="请输入参赛学生"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="比赛级别" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择比赛级别"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMPETITION_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主办方" prop="organizer">
        <el-select
          v-model="queryParams.organizer"
          placeholder="请选择主办方"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMPETITION_ORGANIZER)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="其他主办方" prop="organizerOther" label-width="90px">
        <el-input
          v-model="queryParams.organizerOther"
          placeholder="请输入其他主办方"
          clearable
          @keyup.enter="handleQuery"
          class="!w-[240px]"
        />
      </el-form-item>

      <el-form-item label="指导老师" prop="author">
        <el-select
          v-model="queryParams.author"
          filterable
          remote
          reserve-keyword
          placeholder="请输入名字搜索"
          :remote-method="remoteSearch"
          :loading="userLoading"
          class="!w-240px"
          clearable
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="getUserDisplayName(item.id)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="奖项" prop="rank">
        <el-select
          v-model="queryParams.rank"
          placeholder="请选择奖项"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMPETITION_RANK)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="指导老师成员" prop="member" class="!w-[650px]"  label-width="110px">
        <el-select
          v-model="memberSelectValue"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入名字搜索"
          :remote-method="remoteSearch"
          :loading="userLoading"
          class="!w-[580px]"
          clearable
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="getUserDisplayName(item.id)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="获奖级别" prop="level">
        <el-select
          v-model="queryParams.level"
          placeholder="请选择获奖级别"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMPETITION_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['digital:competition:create']"
        >
          <Icon icon="ep:plus" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['digital:competition:export']"
        >
          <Icon icon="ep:download" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true">
      <el-table-column label="竞赛名称" align="center" prop="name" min-width="120" class-name="wrap-cell">
        <template #default="scope">
          <div class="whitespace-normal break-words">
            {{ scope.row.name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="作品名称" align="center" prop="reserved1" min-width="120" class-name="wrap-cell">
        <template #default="scope">
          <div class="whitespace-normal break-words">
            {{ scope.row.reserved1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="参赛学生" align="center" prop="reserved2" min-width="120" class-name="wrap-cell">
        <template #default="scope">
          <div class="whitespace-normal break-words">
            {{ scope.row.reserved2 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column 
        label="比赛级别" 
        align="center" 
        prop="name" 
        min-width="120"
        class-name="wrap-cell"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMPETITION_TYPE" :value="scope.row.type"  />
        </template>
      </el-table-column>
      <el-table-column label="主办方" align="center" min-width="120" class-name="wrap-cell">
        <template #default="scope">
          <div>
            <div v-if="scope.row.organizer">
              <dict-tag :type="DICT_TYPE.COMPETITION_ORGANIZER" :value="scope.row.organizer || 'dsfds'" :show-tag="false" />
            </div>
            <div v-if="scope.row.organizerOther">{{ scope.row.organizerOther }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="获奖级别" align="center" prop="level">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMPETITION_LEVEL" :value="scope.row.level"  />
        </template>
      </el-table-column>
      <el-table-column 
        label="奖项" 
        align="center" 
        prop="rank"
        min-width="120"
        class-name="wrap-cell"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMPETITION_RANK" :value="scope.row.rank"/>
        </template>
      </el-table-column>
      <el-table-column 
        label="指导老师成员及贡献率" 
        align="center" 
        min-width="250"
      >
        <template #default="scope">
          <div 
            v-if="scope.row.member && scope.row.rate"
            class="whitespace-normal break-words"
          >
            <div 
              v-for="(member, index) in scope.row.member.split(',')" 
              :key="index"
              class="mb-1 last:mb-0"
            >
              {{ getUserNickname(member) }}: {{ scope.row.rate.split(',')[index] }}%
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column 
        label="获奖时间" 
        align="center"
        prop="competitionTime"
        :formatter="dateFormatterYMD"
        width="120"
      />
      <el-table-column 
        label="佐证" 
        align="center" 
        prop="evidenceUrl"
        min-width="150"
      >
        <template #default="scope">
          <div 
            v-if="scope.row.evidenceUrl && Array.isArray(scope.row.evidenceUrl)"
            class="flex flex-wrap justify-center gap-1"
          >
            <el-link
              v-for="(url, index) in scope.row.evidenceUrl"
              :key="index"
              type="primary"
              :href="url"
              target="_blank"
            >
              佐证{{ index + 1 }}
            </el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            v-hasPermi="['digital:competition:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['digital:competition:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CompetitionForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter, dateFormatterYMD } from '@/utils/formatTime'
import CompetitionForm from './CompetitionForm.vue'
import { CompetitionApi, CompetitionVO } from '@/api/digital/competition'
import * as UserApi from '@/api/system/user'
import download from '@/utils/download'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from 'vue-i18n'


defineOptions({ name: 'Competition' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化


const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<CompetitionVO[]>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  type: undefined,
  organizer: undefined,
  level: undefined,
  rank: undefined,
  author: undefined,
  member: undefined,
  organizerOther: '',
  reserved1: '',
  reserved2: ''
})
const queryFormRef = ref() // 搜索表单
const exportLoading = ref(false) // 导出的加载中

// 成员选择的内部值
const memberSelectValue = ref([])

// 监听memberSelectValue变化，更新queryParams.member
watch(memberSelectValue, (newVal) => {
  queryParams.member = newVal.join(',')
}, { deep: true })

// 用户映射
const userMap = ref<Record<string, any>>({})
const userLoading = ref(false)
const userOptions = ref([])

// 初始化用户列表
const initUserOptions = async () => {
  try {
    const data = await UserApi.getAllUser()
    userOptions.value = data
    // 更新用户映射
    data.forEach(user => {
      userMap.value[user.id] = user
    })
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 远程搜索用户
const remoteSearch = async (query: string) => {
  if (query !== '') {
    userLoading.value = true
    try {
      userOptions.value = userOptions.value.filter(item => 
        item.username.toLowerCase().includes(query.toLowerCase()) ||
        (item.nickname && item.nickname.toLowerCase().includes(query.toLowerCase()))
      )
    } finally {
      userLoading.value = false
    }
  } else {
    // 当搜索词为空时，显示所有用户
    await initUserOptions()
  }
}

// 获取用户显示名称
const getUserDisplayName = (userId) => {
  const user = userMap.value[userId]
  if (user) {
    return `${user.username}${user.nickname ? ` (${user.nickname})` : ''}`
  }
  return ''
}

// 获取用户昵称
const getUserNickname = (userId: string) => {
  return userMap.value[userId]?.nickname || userId
}

// 重置查询参数
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.pageNo = 1
  queryParams.member = undefined
  queryParams.reserved1 = ''
  queryParams.reserved2 = ''
  memberSelectValue.value = []
  getList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CompetitionApi.getCompetitionPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await ElMessageBox.confirm('是否确认删除编号为"' + id + '"的数据项?', '警告', {
      type: 'warning'
    })
    // 发起删除
    await CompetitionApi.deleteCompetition(id)
    ElMessage.success('删除成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CompetitionApi.exportCompetition(queryParams)
    download.excel(data, '项目.xls')
  } catch (error) {
    console.error('导出失败:', error)
    message.error(t('common.exportFail'))
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await initUserOptions()
  getList()
})
</script>

<style lang="scss" scoped>
.wrap-cell {
  .cell {
    white-space: normal;
    word-break: break-all;
  }
}
</style>